package com.wisdom.system.service.impl.job;


import com.github.pagehelper.Page;
import com.wisdom.system.dao.job.JobCronMapper;
import com.wisdom.system.entity.job.JobCron;
import com.wisdom.system.entity.base.PageRequest;
import com.wisdom.system.entity.base.PageResult;
import com.wisdom.system.common.annotation.ValidationUnique;
import com.wisdom.system.common.exception.LogicException;
import com.wisdom.system.common.mybatis.PageUtil;
import com.wisdom.system.common.mybatis.SqlUtil;
import com.wisdom.system.service.job.JobCronService;


import org.quartz.impl.triggers.CronTriggerImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

@Service
public class JobCronServiceImpl implements JobCronService {

    private static final Logger LOGGER = LoggerFactory.getLogger(JobCronServiceImpl.class);
    @Autowired
    JobCronMapper jobCronMapper;

    @Override
    @ValidationUnique(key = {"code"}, msg = {"编码已存在！"})
    public int addJobCronInfo(JobCron jobCron) {
        boolean validExpression = isValidExpression(jobCron.getCronExpression());
        if (!validExpression) {
            throw new LogicException("Cron时间格式错误！");
        }
        jobCron.setAddTime(new Date());
        return jobCronMapper.insert(jobCron);
    }

    @Override
    @ValidationUnique(key = {"code"}, msg = {"编码已存在！"}, excludeSelf = true)
    public int updateJobCronInfo(JobCron jobCron) {
        boolean validExpression = isValidExpression(jobCron.getCronExpression());
        if (!validExpression) {
            throw new LogicException("Cron时间格式错误！");
        }
        return jobCronMapper.updateByPrimaryKeySelective(jobCron);
    }

    @Override
    public int delJobCronInfo(String id) {
        return jobCronMapper.deleteByPrimaryKey(id);
    }

    @Override
    public int delJobCronList(String ids) {
        String[] idArray = ids.split(",");
        Example example = new Example(JobCron.class);
        example.createCriteria().andIn("id", Arrays.asList(idArray));
        return jobCronMapper.deleteByExample(example);
    }

    @Override
    public JobCron getJobCronInfo(String id) {
        return jobCronMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<JobCron> getJobCronList(String keyword) {
        return getJobCronExample(keyword);
    }

    @Override
    public PageResult<JobCron> getJobCronPageList(String keyword, PageRequest pageRequest) {
        Page<?> page = PageUtil.startPageAllowNull(pageRequest.getPageNum(), pageRequest.getPageSize());
        return new PageResult<>(getJobCronExample(keyword), page.getTotal());
    }

    /**
     * 获取CRON规则列表、CRON规则分页列表公用方法
     *
     * @param keyword
     * @return
     */
    private List<JobCron> getJobCronExample(String keyword) {
        Example example = new Example(JobCron.class);
        Example.Criteria criteria2 = example.createCriteria();
        criteria2.andLike("name", SqlUtil.likeEscapeH(keyword));
        criteria2.orLike("code", SqlUtil.likeEscapeH(keyword));
        example.and(criteria2);
        example.orderBy("addTime").desc();
        return jobCronMapper.selectByExample(example);
    }

    /**
     * 封装cron表达式验证
     *
     * @param cronExpression
     * @return
     */
    public static boolean isValidExpression(final String cronExpression) {
        CronTriggerImpl trigger = new CronTriggerImpl();
        try {
            trigger.setCronExpression(cronExpression);
            Date date = trigger.computeFirstFireTime(null);
            return date != null && date.after(new Date());
        } catch (Exception e) {
            LOGGER.error("[TaskUtils.isValidExpression]:failed. throw ex:", e);
        }
        return false;
    }
}




